package sein.android.hopenote;

import java.util.ArrayList;
import sein.android.hopenote.Const.HopeNoteDb;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class Item_Input extends Activity {

	private DBAdapter HnopenHelper;
	private SQLiteDatabase sdb;
	private Button bt_i, bt_d, bt_a;
	private EditText et_item, et_unit, et_group;
	private Spinner spin_group, spin_item;
	private Cursor cur_group, cur_item, list_cur;
	private ArrayList<String> lst_group, lst_item, lst_unit;
	private ArrayList<Integer> lst_cnt;
	private ArrayAdapter<String> adapter, adapter_item;
	private ContentValues row; // DB 삽입
	private TextView tv_group, tv_item;
	private String str_group, str_item, str_unit, idx_cnt; // 항목 추가 혹은 삭제 할 때
															// 사용.
	private int idx_group; // 항목 추가 후 ChangeSpinGroup 함수에서 추가한 그룹을 spinner에
							// 지정해주기 위한 index.
	private int idx_item; // 항목 추가 후 ChangeSpinItem 함수에서 추가&수한 항을 spinner에 지정해주기
							// 위한 index.
	private RadioGroup rdo_cnt; // 항목 입력 갯수(단일/복수)

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.item_input);

		bt_i = (Button) findViewById(R.id.bt_insert);
		bt_d = (Button) findViewById(R.id.bt_delete);
		bt_a = (Button) findViewById(R.id.bt_normal_add);
		et_item = (EditText) findViewById(R.id.et_item);
		et_unit = (EditText) findViewById(R.id.et_unit);
		et_group = (EditText) findViewById(R.id.et_group);
		spin_group = (Spinner) findViewById(R.id.sp_group);
		spin_item = (Spinner) findViewById(R.id.sp_item);
		tv_group = (TextView) findViewById(R.id.tv_group);
		tv_item = (TextView) findViewById(R.id.tv_item);
		rdo_cnt = (RadioGroup) findViewById(R.id.rdo_group);

		str_group = "";
		str_item = "";
		str_unit = "";
		idx_cnt = "";

		/*
		 * et_group.setVisibility(View.INVISIBLE);
		 * tv_group.setVisibility(View.INVISIBLE);
		 * et_item.setVisibility(View.INVISIBLE);
		 * tv_item.setVisibility(View.INVISIBLE);
		 */

		HnopenHelper = new DBAdapter(this);
		sdb = HnopenHelper.getReadableDatabase();

		// Note_Add에서 항목관리를 열었을 경우 해당 그룹으로 그룹을 지정해 준다.
		String search_group = HopeNoteDb.CURRENT_GROUP;
		int idx_group = 0;

		// 메인페이지에서 '+' 혹은 메뉴버튼의 '항목관리' 버튼을 누르면 '새 그룹 추가'로 설정한다.
		if (HopeNoteDb.IS_NEW_GROUP) {
			search_group = "";
		}

		Log.i("item", String.valueOf(HopeNoteDb.IS_NEW_GROUP));
		Log.i("item", search_group);

		// set group
		cur_group = sdb.query(true, HopeNoteDb.TB_ITEM,
				new String[] { HopeNoteDb.COL_GROUP }, null, null,
				HopeNoteDb.COL_GROUP, null, null, null);
		cur_group.moveToFirst();
		lst_group = new ArrayList<String>();
		idx_group = cur_group.getCount();

		Log.i("item", String.valueOf(idx_group));

		for (int i = 0; i < cur_group.getCount(); i++) {
			if (cur_group.getString(0).equals(search_group)) {
				idx_group = i;
			}
			lst_group.add(cur_group.getString(0));
			cur_group.moveToNext();
		}
		if (cur_group.getCount() < 9) {
			lst_group.add("새 그룹 추가");
		}
		cur_group.close();
		spin_group.setPrompt("그룹 선택");
		adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, lst_group);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spin_group.setAdapter(adapter);

		Log.i("item", String.valueOf(idx_group));

		if (idx_group > 8) {
			idx_group = 0;
		}
		spin_group.setSelection(idx_group);

		// set item & unit
		String qWhere = HopeNoteDb.COL_GROUP + " = '"
				+ spin_group.getSelectedItem().toString() + "'";

		Log.i("item", qWhere);

		cur_item = sdb.query(HopeNoteDb.TB_ITEM, new String[] {
				HopeNoteDb.COL_ITEM, HopeNoteDb.COL_UNIT, HopeNoteDb.COL_CNT },
				qWhere, null, null, null, null);
		cur_item.moveToFirst();
		lst_item = new ArrayList<String>();
		lst_unit = new ArrayList<String>();
		lst_cnt = new ArrayList<Integer>();
		for (int i = 0; i < cur_item.getCount(); i++) {
			lst_item.add(cur_item.getString(0));
			lst_unit.add(cur_item.getString(1));
			lst_cnt.add(cur_item.getInt(2));
			cur_item.moveToNext();
		}
		cur_item.close();
		lst_item.add("새 항목 추가");
		spin_item.setPrompt("항목 선택");
		adapter_item = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, lst_item);
		adapter_item
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spin_item.setAdapter(adapter_item);

		Log.i("item", "end");

		// group Selection Event
		spin_group
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						TextView tv = (TextView) arg1;
						if (tv.getText().toString().equals("새 그룹 추가")) {
							/*
							 * et_group.setVisibility(View.VISIBLE);
							 * tv_group.setVisibility(View.VISIBLE);
							 * et_item.setVisibility(View.VISIBLE);
							 * tv_item.setVisibility(View.VISIBLE);
							 */

							bt_i.setText("추가");
							bt_i.setTag("add");
							bt_i.setTextColor(Color.BLACK);
							bt_d.setClickable(false);
							bt_d.setTextColor(Color.GRAY);

							et_group.setText("");
							et_item.setText("");
							et_unit.setText("");
							rdo_cnt.check(R.id.rdo_1);
							idx_cnt = "1";

							str_item = "";
						} else {
							/*
							 * et_group.setVisibility(View.INVISIBLE);
							 * tv_group.setVisibility(View.INVISIBLE);
							 */

							et_group.setText(tv.getText().toString());
						}
						Log.i("item", "group event");
						ChangeSpinItem();
					}

					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub

					}
				});

		// Item Selection Event
		spin_item
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						TextView tv = (TextView) arg1;
						if (tv.getText().toString().equals("새 항목 추가")) {
							// et_item.setVisibility(View.VISIBLE);
							// tv_item.setVisibility(View.VISIBLE);
							bt_i.setText("추가");
							bt_i.setTag("add");
							// bt_i.setClickable(true);
							bt_i.setTextColor(Color.BLACK);
							// bt_i.setTextColor()
							bt_d.setClickable(false);
							bt_d.setTextColor(Color.GRAY);

							et_item.setText("");
							et_unit.setText("");
							rdo_cnt.check(R.id.rdo_1);
							idx_cnt = "1";

							str_item = "";
						} else {
							// et_item.setVisibility(View.INVISIBLE);
							// tv_item.setVisibility(View.INVISIBLE);
							// bt_i.setClickable(false);
							// bt_i.setTextColor(Color.GRAY);
							et_item.setText(tv.getText().toString());
							bt_i.setText("수정");
							bt_i.setTag("modify");
							bt_d.setClickable(true);
							bt_d.setTextColor(Color.BLACK);

							et_unit.setText(lst_unit.get(spin_item
									.getSelectedItemPosition()));
							switch (lst_cnt.get(spin_item
									.getSelectedItemPosition())) {
							case 1:
								rdo_cnt.check(R.id.rdo_1);
								break;
							case 2:
								rdo_cnt.check(R.id.rdo_2);
							}

							str_item = tv.getText().toString();
						}
						
						Log.i("item", "아이템 선택 : "+str_item);
					}

					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub

					}
				});

		// 입력 수 선태
		rdo_cnt.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// TODO Auto-generated method stub
				switch (checkedId) {
				case R.id.rdo_1:
					idx_cnt = "1";
					break;
				case R.id.rdo_2:
					idx_cnt = "2";
					break;
				}
			}
		});

		// 항목 수정 & 추가
		bt_i.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub

				// check group selection
				if (et_group.getText().toString().replace(" ", "").equals("")) {
					Toast.makeText(Item_Input.this, "그룹을 입력해주세요.",
							Toast.LENGTH_SHORT).show();
					et_group.requestFocus();
					return;
				}
				/*
				 * if(spin_group.getSelectedItem().toString().equals("새 그룹 추가"))
				 * { if(et_group.getText().toString().replace(" ",
				 * "").equals("")) { Toast.makeText(Item_Input.this,
				 * "그룹을 입력해주세요.", Toast.LENGTH_SHORT).show();
				 * et_group.requestFocus(); return; } else { str_group =
				 * et_group.getText().toString().replace(" ", "").trim(); } }
				 * else { str_group =
				 * spin_group.getSelectedItem().toString().trim(); }
				 */

				// check item name
				if (et_item.getText().toString().trim().equals("")) {
					Toast.makeText(Item_Input.this, "항목 이름을 입력해주세요.",
							Toast.LENGTH_SHORT).show();
					et_item.requestFocus();
					return;
				}

				str_group = et_group.getText().toString().replace(" ", "");
				str_item = et_item.getText().toString().replace(" ", "");
				str_unit = et_unit.getText().toString().replace(" ", "");

				String qWhere = HopeNoteDb.COL_ITEM + " = '" + str_item + "'";
				list_cur = sdb.query(HopeNoteDb.TB_ITEM, new String[] { "1" },
						qWhere, null, null, null, null);

				row = new ContentValues();
				row.put(HopeNoteDb.COL_GROUP, str_group);
				row.put(HopeNoteDb.COL_ITEM, str_item);
				row.put(HopeNoteDb.COL_UNIT, str_unit);
				row.put(HopeNoteDb.COL_CNT, idx_cnt);

				// 항목 추가
				if (v.getTag().toString().equals("add")) {
					if (list_cur.getCount() == 0) {
						if (sdb.insert(HopeNoteDb.TB_ITEM, null, row) > 0) {
							Toast.makeText(Item_Input.this, "추가 완료",
									Toast.LENGTH_SHORT).show();
							// et_group.setText("");
							// et_item.setText("");
							// et_unit.setText("");
							ChangeSpinGroup();
							ChangeSpinItem();
						} else {
							Toast.makeText(Item_Input.this, "실패",
									Toast.LENGTH_SHORT).show();
						}
					} else {
						Toast.makeText(Item_Input.this, "항목이 존재합니다.",
								Toast.LENGTH_SHORT).show();
						et_item.requestFocus();
					}
				}
				// 항목 수정
				else if (v.getTag().toString().equals("modify")) {
					qWhere = HopeNoteDb.COL_ITEM + " = '"
							+ spin_item.getSelectedItem().toString().trim()
							+ "'";
					if (sdb.update(HopeNoteDb.TB_ITEM, row, qWhere, null) > 0) {
						Toast.makeText(Item_Input.this, "수정 완료",
								Toast.LENGTH_SHORT).show();
						ChangeSpinGroup();
						ChangeSpinItem();
					} else {
						Toast.makeText(Item_Input.this, "실패",
								Toast.LENGTH_SHORT).show();
					}
				}

			}
		});

		// 항목 삭제
		bt_d.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				// check group selection
				str_group = spin_group.getSelectedItem().toString();
				str_item = spin_item.getSelectedItem().toString();

				String qWhere = HopeNoteDb.COL_ITEM + " = '" + str_item + "'";
				if (sdb.delete(HopeNoteDb.TB_ITEM, qWhere, null) > 0) {
					Toast.makeText(Item_Input.this, "삭제 완료", Toast.LENGTH_SHORT)
							.show();
					
					bt_i.setText("추가");
					bt_i.setTag("add");
					bt_i.setTextColor(Color.BLACK);
					bt_d.setClickable(false);
					bt_d.setTextColor(Color.GRAY);

					et_group.setText("");
					et_item.setText("");
					et_unit.setText("");
					rdo_cnt.check(R.id.rdo_1);
					idx_cnt = "1";

					str_item = "";
					
					ChangeSpinItem();
				} else {
					Toast.makeText(Item_Input.this, "삭제 실패", Toast.LENGTH_SHORT)
							.show();
				}
			}
		});

		// 정상 범위 등록
		bt_a.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				// View new Group Noamal_Add.java
				Intent nomal_add = new Intent(Item_Input.this, Normal_Add.class);
				startActivity(nomal_add);

			}

		});
	}

	// reset spinner-group by addition or deletion
	private void ChangeSpinGroup() {
		// set group
		cur_group = sdb.query(HopeNoteDb.TB_ITEM,
				new String[] { HopeNoteDb.COL_GROUP }, null, null,
				HopeNoteDb.COL_GROUP, null, null);
		// lst_group = new ArrayList<String>();
		lst_group.clear();
		idx_group = cur_group.getCount();

		if (idx_group > 0)
			cur_group.moveToFirst();

		Log.i("item", str_group);

		for (int i = 0; i < cur_group.getCount(); i++) {
			lst_group.add(cur_group.getString(0));
			if (str_group.equals(cur_group.getString(0))) {
				idx_group = i;
			}
			cur_group.moveToNext();
		}
		if (cur_group.getCount() < 9) {
			lst_group.add("새 그룹 추가");
		}
		cur_group.close();
		adapter.notifyDataSetChanged();
		if (idx_group > 8) {
			idx_group = 0;
		}
		spin_group.setSelection(idx_group); // call ChangeSpinItem by
											// setOnItemSelectedListener
	}

	// reset spinner-item by spinner-group selection change.
	private void ChangeSpinItem() {
		// set item & unit
		String qWhere = HopeNoteDb.COL_GROUP + " = '"
				+ spin_group.getSelectedItem().toString() + "'";
		Log.i("item", "chgspinitem qWhere : " + qWhere);
		cur_item = sdb.query(HopeNoteDb.TB_ITEM, new String[] {
				HopeNoteDb.COL_ITEM, HopeNoteDb.COL_UNIT, HopeNoteDb.COL_CNT },
				qWhere, null, null, null, null);
		Log.i("item", String.valueOf(cur_item.getCount()));
		lst_item.clear();
		lst_unit.clear();
		lst_cnt.clear();
		Log.i("item", String.valueOf(cur_item.getCount()));

		idx_item = cur_item.getCount();
		if (idx_item > 0)
			cur_item.moveToFirst();

		Log.i("item", str_item);

		for (int i = 0; i < cur_item.getCount(); i++) {
			if (str_item.equals(cur_item.getString(0))) {
				idx_item = i;
			}
			lst_item.add(cur_item.getString(0));
			lst_unit.add(cur_item.getString(1));
			lst_cnt.add(cur_item.getInt(2));
			cur_item.moveToNext();
		}
		Log.i("item", String.valueOf(idx_item));
		lst_item.add("새 항목 추가");
		adapter_item.notifyDataSetChanged();
		spin_item.setSelection(idx_item);
		cur_item.close();

		/*
		 * if(spin_item.getSelectedItem().toString().equals("새 항목 추가")) {
		 * unit.setText(""); } else {
		 * unit.setText(lst_unit.get(spin_item.getSelectedItemPosition())); }
		 */
		Log.i("item", "changeSpinItem");
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		Intent intent = new Intent("Note_Input_btSet");
		sendBroadcast(intent);
		HopeNoteDb.IS_NEW_GROUP = false;
		finish();
	}
}
